package com.qk.management.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.CURDEnum;
import com.qk.common.exception.CommonException;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Role> getAll() {
        return roleMapper.selectAll();
    }


    @Override
    public void updateRole(Role role) {
        role.setUpdateTime(LocalDateTime.now());
        System.out.println(role);
        roleMapper.update(role.getId(),role.getName(),role.getLabel(),role.getRemark(),role.getUpdateTime());
        System.out.println(role);
    }



    @Override
    public Role getRoleById(Integer id) {
        return roleMapper.selectRoleById(id);
    }

    @Override
    public void addRole(Role role) {
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.insert(role);
    }



    @Override
    public void deleteById(Integer id) {
        List<User> users = userMapper.selectUserByRole(roleMapper.selectRoleById(id).getLabel());
        if (users != null && users.size() > 0){
            CommonException.throwCommonException(CURDEnum.DELETE_ERROR);
        }
        roleMapper.delete(id);
    }


    @Override
    public PageResult<Role> getAllRoles(String name, String label, Integer page, Integer pageSize) {
        // 开始分页
        PageHelper.startPage(page, pageSize);

        // 执行查询
        List<Role> roles = roleMapper.selectAllRoles(name, label);

        // 获取分页信息
        Page<Role> pageInfo = (Page<Role>) roles;

        // 封装成 PageResult 对象
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getResult());
    }


}
